<template>
  <el-cascader v-model="departments"
               :props="cascaderProps"
               ref="DepartmentCascader"
               :options="departmentList"></el-cascader>
</template>

<script>
export default {
  name: "DepartmentCascader",
  props: {
  },
  components: {

  },
  data () {
    return {
      // 级联选择器配置项
      cascaderProps: {
        expandTrigger: 'click',
        value: 'id',
        label: 'department_name',
        children: 'children',
        lazy: true,
        // 懒加载
        lazyLoad: this.LoadDepartmentChildren
      },
      // 部门列表
      departmentList: [],
      // 部门
      departments: "",
      selectedNode: {},
    };
  },
  computed: {
  },
  watch: {
    departments: {
      deep: true,
      immediate: true,
      handler (val, oldval) {
        let departmentId = val[val.length - 1]
        // this.$store.commit("user/SETDEPARTMENTID", departmentId)
      }
    }
  },
  created () {

  },
  mounted () {
    this.$nextTick(() => {
      this.getDepartmentData()
    })
  },
  methods: {
    // 子节点部门获取
    async LoadDepartmentChildren (node, resolve) {
      console.log(node)
      // if (!node) return
      if (!node.data) return
      const children = await this.$API.department.getListByAncestorId(node.data.id)
      if (children && children.status == 200) {
        if (Array.isArray(children.data) && children.data.length == 0) {
          this.$emit("SelectDepartment", node.data.id)
          this.$refs.DepartmentCascader.visible = false
          //   console.log(this.departmentId[this.departmentId.length-1])
          // this.$store.state.user.departmentId=this.departmentId[-1]
        }
        resolve(children.data)
      } else {
        resolve([])
      }
    },
    // 获取部门数据
    async getDepartmentData () {
      const res = await this.$API.department.getRootDepartment()
      // console.log(res)
      if (res.status == 200) {
        this.departmentList = res.data
      }
    }

  }}
</script>

<style scoped lang="less">
</style>
